package com.sq.partner.manager.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.Message;
import com.sq.partner.manager.Message.Type;
import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.GatewayCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.DeptDto;
import com.sq.partner.manager.mybatis.model.GatewayMenuUri;
import com.sq.partner.manager.mybatis.model.GatewayRoleDept;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.GatewayUserRole;
import com.sq.partner.manager.service.IGatewayMenuUriService;
import com.sq.partner.manager.service.IGatewayRoleDeptService;
import com.sq.partner.manager.service.IGatewayUserLoginService;
import com.sq.partner.manager.service.IGatewayUserService;
import com.sq.partner.manager.sso.UMClient;
import com.sq.partner.manager.sso.webservice.UserInfo;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.MD5Util;
import com.sq.partner.manager.util.StrUtil;

/**
 * 用户登录Controller
 * @author zhihuizhao
 *
 */
@Controller
public class LoginController {
	
	private static Logger logger = LogUtil.getLog(LoginController.class);
	
	@Resource
	private IGatewayUserLoginService iGatewayUserLoginService;
	@Resource
	private IGatewayUserService userSerive;
	@Resource
	private IGatewayRoleDeptService roledeptService;
	@Resource
	private IGatewayMenuUriService menuUriService;
	
	/**
	 * 登录成功后，进入首页
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/showIndex")
	public String showIndex(Model model)
	{
		return "index";
	}
	
	/**
	 * 过滤器判断没有登录成功即跳转至登录页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/showLogin")
	public String checkingLogin(Model model,HttpServletRequest request,String errorcode)
	{   
		if("1".equals(errorcode)){
			request.setAttribute("errorMsg", "未登录或登录已过期，请重新登录");
		}
		return "login";
	}
	
	/**
	 * 在此方法中进行登录校验，如果没有错误，登录成功，并将当前用户对象保存在session中，在保存user对象之前，
	 * 获取该用户的所有权限机构及其子机构保存在user对象中的List<DeptDto> 属性里
	 * 否则抛出相应异常并跳转至登录页显示错误信息
	 * 注：校验密码时要先用MD5加密此密码再去数据库比较;
	 * @param user
	 * @param str
	 * @param model
	 * @param usercode
	 * @param userpwd
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkLogin",method=RequestMethod.POST)
	 public @ResponseBody Result checkLogin(ModelMap model,HttpServletRequest request,String usercode,String userpwd,GatewayUser user) throws Exception {
		logger.debug("页面用户名:"+usercode + " 密码: "+ userpwd);
		if(StrUtil.isEmpty(usercode)){
			return Result.error("请输入用户名");
		}else if(StrUtil.isEmpty(userpwd)){
			return Result.error("请输入密码");
		}else{
			HttpSession session = request.getSession();
			String switchValue = GatewayCache.getCache(Constants.LOGIN_SWITCH_VALUE);
			if(Constants.SWITCH_VALUE_LOCAL.equals(switchValue)){//本地登陆
				Map<String, String> usermap = new HashMap<String, String>();
				usermap.put("userCode",usercode);
				usermap.put("userPwd", MD5Util.md5(userpwd));
				
				GatewayUser gatewayuser = iGatewayUserLoginService.checkLogin(usermap);
				if(gatewayuser==null){
					return Result.error("用户名或密码不正确，请重新输入");
				}else
				{
					if(gatewayuser.getStatus()==2){
						return Result.error("用户名或密码错误");
					}else
					{
						//补充权限、菜单信息
						addDeptMenuInfo(gatewayuser);
						//设置登陆方式
						gatewayuser.setSwitchValue(switchValue);
						session.setAttribute(Constants.SESSION_USER,gatewayuser);
						logger.info("用户:[" + gatewayuser.getUserName()+"]登陆成功,登陆方式"+switchValue );
						//登录成功，更新该用户最后一次登录时间
						gatewayuser.setLastLogintime(getCurdate());
						userSerive.saveUser(gatewayuser);
					}
				}
			}else if(Constants.SWITCH_VALUE_UM.equals(switchValue)){//UM登陆
				UserInfo ui = UMClient.authBackInfo(usercode, userpwd, request.getRemoteAddr());
				if(ui == null){
					return Result.error("用户名或密码不正确，请重新输入");
				}else if (Constants.UM_USER_STATUS_LOCKED.endsWith(ui.getUserStatus())){
					return Result.error("用户已锁定，请在UM系统解锁该用户");
				}else{
					GatewayUser gatewayuser = iGatewayUserLoginService.queryUser(ui.getUserId());
					if(gatewayuser == null){
						return Result.error("用户名或密码错误");
					}else{
						if(gatewayuser.getStatus()==2){
							return Result.error("用户名或密码错误");
						}else{
							//补充权限、菜单信息
							addDeptMenuInfo(gatewayuser);
							//设置登陆方式
							gatewayuser.setSwitchValue(switchValue);
							session.setAttribute(Constants.SESSION_USER,gatewayuser);
							logger.info("用户:[" + gatewayuser.getUserName()+"]登陆成功,登陆方式"+switchValue);
							//登录成功，更新该用户最后一次登录时间
							gatewayuser.setLastLogintime(getCurdate());
							userSerive.saveUser(gatewayuser);
						}
					}
				}
			}else if(Constants.SWITCH_VALUE_SSO.endsWith(switchValue)){
				//SSO登陆已在单点登陆filter处理
			}else{
				return Result.error("未知登陆方式["+switchValue+"]");
			}
		}
		
		return Result.success("登陆成功");
    }
	
	private void addDeptMenuInfo(GatewayUser user) throws Exception{
		//给user对象的权限机构list赋值
		List<DeptDto> list = roledeptService.queryDeptDto(user.getUserid());
		if(null!=list && list.size() >0){
			user.setDepartmentStr(deptStr(list));
			user.setDepts(list);
		}
		
		//给user对象的菜单list赋值
		List<GatewayMenuUri> menuuriList = menuUriService.queryLoginUserMenuUri(user.getUserid());
		List<String> urilist = new ArrayList<String>();
		if(null!=menuuriList && menuuriList.size()>0){
			for(int i=0;i<menuuriList.size();i++){
				urilist.add(menuuriList.get(i).getUri());
			}
			user.setUriList(urilist);
		}
	}
	
	/***
	 * 用户点击”退出“按钮后，页面将跳转至登录页面，删除session中的用户并销毁session
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/logout")
	public String logout(HttpServletRequest request,HttpServletResponse response)
	{
		HttpSession session = request.getSession(); 
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		String switchValue = GatewayCache.getCache(Constants.LOGIN_SWITCH_VALUE);
		String userName = "";
		if(user != null){
			userName = user.getUserName();
		}
		session.invalidate();
		logger.info("用户:[" + userName+"]已退出登陆");
		if(Constants.SWITCH_VALUE_SSO.equals(switchValue)){
			return "redirect:"+ Config.getProp(Constants.SSO_LOGOUT_URL)+ "?service="+response.encodeURL(getLoginUrl(request));
		}else{
			return "login";
		}
		
	}
	
	public static String getLoginUrl(HttpServletRequest request){
		StringBuffer url = new StringBuffer();
		if(request.isSecure()){
			url.append("https");
		}else{
			url.append("http");
		}
		
		url.append("://");
		url.append(request.getServerName());
		int port = request.getServerPort();
		if(port != 80){
			url.append(":").append(port);
		}
		
		url.append(request.getContextPath());
		url.append("/showIndex");
		return url.toString();
	}
	
	
	/**
	 * 当前用户角色机构集合转换成字符串
	 * @param depts
	 * @return
	 * @throws Exception
	 */
	public static String deptStr(List<DeptDto> depts) throws Exception{
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<depts.size();i++){
			sb.append("'"+depts.get(i).getDeptCode()+"',");
		}
		String deptStr = sb.toString();
		deptStr = deptStr.substring(0,deptStr.length()-1);
		return deptStr;
	}

	
	/**
	 * 获取系统当前时间
	 * @return
	 * @throws Exception
	 */
	public static Date getCurdate() throws Exception{
		Date dt = new Date();
		return dt;
	}

}
